import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch, Link, } from "react-router-dom";
import { createForm } from 'rc-form';
import { Layout, Empty, Tag, Card, Icon, Button, Divider, message, Skeleton } from "antd";
import { Calendar, WingBlank, WhiteSpace, List, InputItem, Flex, ActivityIndicator, Picker, PullToRefresh } from 'antd-mobile';
import {
    getAllSmokeDeviceRecordBySchoolIdApi, getSearchSmokeDeviceRecordApi,
    getSingleSmokeDeviceRecordApi,
} from "../js/api.js";
import zhCN from 'antd-mobile/lib/calendar/locale/zh_CN';
import '../css/wechatmobile.css';
import md5 from 'md5';
import moment from 'moment';
import { iconFontUrl } from "../js/config.js";
import $ from 'jquery';

const echarts = require('echarts');
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,
});


class WeChatSmokeDevice extends Component {

    constructor(props) {
        super(props);
        this.state = {
        };
    }




    render() {
        return (
            <Router basename="wechatsmokedevice">
                <Layout style={{ backgroundColor: '#f5f5f5' }}>
                    <Layout.Content>
                        <Route path="/history" component={WeChatSmokeDeviceHistory} />
                        <Route path="/" component={WeChatSmokeDeviceMain} />
                    </Layout.Content>
                </Layout>
            </Router>
        );
    }
}

class weChatSmokeDeviceMain extends Component {
    originbodyScrollY = document.getElementsByTagName('body')[0].style.overflowY;

    constructor(props) {
        super(props);
        this.state = {
            listLoading: true,
            listData: [],
            currentListData: [],
            departmentId: this.getUrlParam("departmentId"),
            // departmentId: 4,
            deviceIdArr: [],
            deviceNameArr: [],
            deviceAddressArr: [],
            deviceStatusData: {
                '00': 0,
                '01': 0,
                '02': 0,
                '03': 0,
                '04': 0,
                '05': 0,
                '06': 0,
                'sum': 0
            },

            isSearch: false,
            isSearchOpen: false, //指form是否弹出
            searchChartLoading: false,
            chartSearchData: {
                timestamp: [],
                time: []
            },

            deviceStatusArr: [{
                value: '00',
                label: '正常'
            }, {
                value: '01',
                label: '烟雾报警'
            }, {
                value: '02',
                label: '防拆异常'
            }, {
                value: '03',
                label: '电压异常'
            }, {
                value: '04',
                label: '通信故障'
            }, {
                value: '05',
                label: '设备故障'
            }, {
                value: '06',
                label: '其他故障'
            }],
            deviceStatusObject: {
                '00': '正常',
                '01': '烟雾报警',
                '02': '防拆异常',
                '03': '电压异常(电压低于2.9V)',
                '04': '通信故障',
                '05': '设备故障',
                '06': '其他故障'
            },

            calendarShow: false,
            startTime: undefined,
            endTime: undefined,

            refreshing: false,
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            listLoading: true
        });
        let listData = [];
        let currentListData = [];
        let deviceIdArr = [];
        let deviceNameArr = [];
        let deviceAddressArr = [];
        getAllSmokeDeviceRecordBySchoolIdApi(parseInt(this.state.departmentId))
            .then((res) => {
                res.data.table.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    listData.push({
                        key: index + 1,
                        deviceId: item.deviceId,
                        name: item.name,
                        address: item.address,
                        deviceStatus: item.deviceStatus,
                        fireAlarm: item.fireAlarm,
                        smokeConc: item.smokeConc,
                        envTemp: item.envTemp,
                        batteryVoltage: item.batteryVoltage,
                        tamper: item.tamper,
                        timestamp: item.timestamp,
                    });
                    deviceIdArr.push(item.deviceId);
                    deviceNameArr.push(item.name);
                    deviceAddressArr.push(item.address);
                });

                if (listData.length > 5) {
                    currentListData = listData.slice(0, 5);
                } else {
                    currentListData = listData.slice(0, listData.length);
                }

                this.setState({
                    listData: listData,
                    currentListData: currentListData,
                    deviceIdArr: deviceIdArr,
                    deviceNameArr: deviceNameArr,
                    deviceAddressArr: deviceAddressArr,
                    listLoading: false,
                    deviceStatusData: res.data.nums
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    showHistory = (deviceId) => {
        this.props.history.push({ pathname: "/history", state: { deviceId } });
    }

    handleHoverButtom = () => {
        this.setState({
            isSearchOpen: !this.state.isSearchOpen,
        }, () => {
            if (this.state.isSearchOpen) {
                $('.am-pull-to-refresh').animate({
                    scrollTop: $(".am-pull-to-refresh-content-wrapper").offset().top
                }, 1000);
            } else {
                this.setState({ isSearch: false });
                this.refreshData();
            }
        });
    }


    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((error, values) => {
            values.address = values.address || undefined;
            values.deviceId = values.deviceId || undefined;
            values.name = values.name || undefined;
            if (values.fireAlarm != undefined) { values.fireAlarm = values.fireAlarm[0]; }
            if (values.tamper != undefined) { values.tamper = values.tamper[0]; }
            values.timePre = this.state.startTime;
            values.timeAfter = this.state.endTime;
            values.smokeConc = {
                numberLittle: values.smokeConcLittle,
                numberLarge: values.smokeConcLarge,
            }
            console.log(values)

            if (values.address == undefined && values.deviceId == undefined
                && (values.deviceStatus == undefined || values.deviceStatus.length == 0) && values.fireAlarm == undefined
                && values.name == undefined && values.smokeConcLarge == undefined && values.smokeConcLittle == undefined
                && values.tamper == undefined && values.timePre == undefined && values.timeAfter == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    listLoading: true,
                    searchChartLoading: true,
                    isSearch: true,
                });

                if (values.deviceStatus != undefined && values.deviceStatus.length == 0) {
                    values.deviceStatus = undefined;
                }
                getSearchSmokeDeviceRecordApi(parseInt(this.state.departmentId), values)
                    .then((res) => {
                        console.log(res)
                        let listData = [];
                        res.data.table.forEach((item, index) => {
                            //console.log("getAllUser", item);
                            listData.push({
                                key: index + 1,
                                deviceId: item.deviceId,
                                name: item.name,
                                address: item.address,
                                deviceStatus: item.deviceStatus,
                                fireAlarm: item.fireAlarm,
                                smokeConc: item.smokeConc,
                                envTemp: item.envTemp,
                                batteryVoltage: item.batteryVoltage,
                                tamper: item.tamper,
                                timestamp: item.timestamp,
                            });
                        });
                        this.setState({
                            listData: listData,
                            listLoading: false,
                            alertVisible: false,
                            chartSearchData: res.data.echarts,
                            searchChartLoading: false,
                        });
                        if (listData.length > 5) {
                            this.setState({
                                currentListData: listData.slice(0, 5)
                            })
                        } else {
                            this.setState({
                                currentListData: listData.slice(0, listData.length)
                            })
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        });
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
        });
        this.refreshData();
    }

    calendarConfirm = (startTime, endTime) => {
        document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
        this.setState({
            calendarShow: false,
            startTime: new Date(startTime).getFullYear() + '/'
                + new Date(startTime).getMonth() + '/'
                + new Date(startTime).getDate(),
            endTime: new Date(endTime).getFullYear() + '/'
                + new Date(endTime).getMonth() + '/'
                + new Date(endTime).getDate(),
        });
    }

    calendarCancel = () => {
        document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
        this.setState({
            calendarShow: false,
            startTime: undefined,
            endTime: undefined,
        });
    }

    listRefresh = () => {
        this.setState({ refreshing: true });
        let listData = [...this.state.listData];
        let currentListData = [...this.state.currentListData];
        setTimeout(() => {
            if (listData.length == currentListData.length) {
                message.info('已经是最后一条数据');
            } else if (listData.length - currentListData.length <= 5) {
                this.setState({ currentListData: listData });
            } else {
                this.setState({
                    currentListData: currentListData.concat(...[listData.slice(currentListData.length, currentListData.length + 5)])
                }, () => { console.log(this.state.currentListData.length) })
            }
            this.setState({ refreshing: false });
        }, 500);
    }


    render() {
        const { getFieldProps, getFieldError } = this.props.form;
        const { deviceStatusData } = this.state;
        const pathname = this.props.history.location.pathname;

        let cardList;
        if (this.state.currentListData.length != 0) {
            cardList = this.state.currentListData.map((value, index) => {
                let content = [{
                    title: '设备编号',
                    value: (<span style={{ fontSize: document.body.clientWidth < 345 ? 12 : 14 }}>{value.deviceId}</span>)
                }, {
                    title: '设备名称',
                    value: (<span style={{ fontSize: document.body.clientWidth < 345 ? 12 : 14 }}>{value.name}</span>)
                }, {
                    title: '设备地址',
                    value: (<div>{value.address}</div>)
                }, {
                    title: '设备状态',
                    value: (
                        <div>
                            {value.deviceStatus == '00' ?
                                (
                                    <Tag color={'green'}>{this.state.deviceStatusObject[value.deviceStatus]}</Tag>
                                ) : (
                                    <Tag color={'red'}>{this.state.deviceStatusObject[value.deviceStatus]}</Tag>
                                )
                            }
                        </div>
                    )
                }, {
                    title: '火警状态',
                    value: (
                        <div>
                            {value.fireAlarm == 0 ? ('非火警') : ('火警')}
                        </div>
                    )
                }, {
                    title: '烟雾浓度',
                    value: (
                        <div>
                            {value.timestamp != 0 ? (<Tag color={'orange'}>{value.smokeConc} mg/m³</Tag>) : (
                                value.smokeConc == 0 ?
                                    (
                                        <Tag color={'green'}>正常无反馈</Tag>
                                    ) : (
                                        <Tag color={'orange'}>{value.smokeConc} mg/m³</Tag>
                                    )
                            )
                            }
                        </div>
                    )
                }, {
                    title: '环境温度',
                    value: (
                        <div>
                            {value.timestamp != 0 ? (value.envTemp + ' ℃') : (
                                value.envTemp == 0 ?
                                    (
                                        <Tag color={'green'}>正常无反馈</Tag>
                                    ) : (
                                        value.envTemp + ' ℃'
                                    )
                            )
                            }
                        </div>)
                }, {
                    title: '工作电压',
                    value: (<div>{value.batteryVoltage + ' V'}</div>)
                }, {
                    title: '防拆情况',
                    value: (
                        <div>
                            {value.tamper == '00' ?
                                (
                                    <Tag color={'green'}>正常</Tag>
                                ) : (
                                    <Tag color={'red'}>防拆盖脱离</Tag>
                                )
                            }
                        </div>
                    )
                }, {
                    title: '最近反馈时间',
                    value: (
                        <div>{
                            value.timestamp == '0' ? (
                                <Tag color={'green'}>正常无反馈</Tag>
                            ) : (
                                    <span style={{ fontSize: 12 }}>{value.timestamp}</span>
                                )}
                        </div>
                    )
                }];

                let contentCard = content.map((d, index) =>
                    <Card
                        size="small"
                        title={d.title}
                        headStyle={{ padding: '0 8px' }}
                        bodyStyle={{ height: 38, padding: 8 }}
                        className='upAndDownInnerCardHalf'>
                        {d.value}
                    </Card>
                )

                return (
                    <Link
                        style={{ textDecoration: 'none' }}
                        to={{
                            pathname: '/history',
                            state: {
                                deviceId: value.deviceId,
                                name: value.name,
                                address: value.address,
                                departmentId: this.state.departmentId
                            }
                        }}>
                        <Card
                            className='conditionCard'
                            headStyle={{ padding: '0 16px' }}
                            bodyStyle={{ padding: '10px' }}
                            title={"序号: " + value.key}
                            extra={(
                                <span style={{ fontSize: 14, color: '#1890ff' }}>
                                    {'反馈历史 >'}
                                </span>
                            )}>
                            <Flex
                                justify="between"
                                wrap='wrap'
                                style={{ marginBottom: '-8px' }}>
                                {contentCard}
                            </Flex>
                        </Card>
                    </Link>
                )
            });
        } else {
            cardList = (<Empty />);
        }

        return (
            <div>
                <PullToRefresh
                    style={{
                        height: document.documentElement.clientHeight,
                        overflow: 'auto',
                    }}
                    damping={60}
                    ref={el => this.ptr = el}
                    indicator={{ deactivate: '上拉可以刷新', }}
                    direction={'up'}
                    refreshing={this.state.refreshing}
                    onRefresh={this.listRefresh}>
                    {this.state.isSearchOpen ? (
                        <form style={{ textAlign: 'center' }}>
                            <Divider>数据搜索</Divider>
                            <InputItem
                                placeholder="支持模糊搜索"
                                clear
                                {...getFieldProps('deviceId', {
                                    rules: [{ required: false }],
                                })}>设备编号</InputItem>
                            <InputItem
                                placeholder="支持模糊搜索"
                                clear
                                {...getFieldProps('name', {
                                    rules: [{ required: false }],
                                })}>设备名称</InputItem>
                            <InputItem
                                placeholder="支持模糊搜索"
                                clear
                                {...getFieldProps('address', {
                                    rules: [{ required: false }],
                                })}>设备地址</InputItem>
                            <Picker
                                data={this.state.deviceStatusArr}
                                cols={1}
                                {...getFieldProps('deviceStatus', {
                                    rules: [{ type: 'array', required: false }],
                                })}>
                                <List.Item arrow="horizontal">设备状态</List.Item>
                            </Picker>
                            <Picker
                                data={[{ value: 1, label: '火警' }, { value: 2, label: '非火警' }]}
                                cols={1}
                                {...getFieldProps('fireAlarm', {
                                    rules: [{ required: false }],
                                })}>
                                <List.Item arrow="horizontal">火警状态</List.Item>
                            </Picker>
                            <Flex
                                style={{ backgroundColor: '#fff' }}
                                wrap='nowrap'
                                justify='center'>
                                <div style={{ flex: 6 }}>
                                    <InputItem
                                        type="digit"
                                        placeholder="0 mg/m³"
                                        clear
                                        {...getFieldProps('smokeConcLittle', {
                                            rules: [{ required: false, pattern: /^[0-9]+$/ }],
                                        })}>烟雾浓度</InputItem>
                                </div>
                                ~
                            <div style={{ flex: 4 }}>
                                    <InputItem
                                        type="digit"
                                        placeholder="∞ mg/m³"
                                        clear
                                        {...getFieldProps('smokeConcLarge', {
                                            rules: [{ required: false, pattern: /^[0-9]+$/ }],
                                        })} />
                                </div>
                            </Flex>
                            <Picker
                                data={[{ value: 0, label: '正常' }, { value: 1, label: '防拆盖脱离' }]}
                                cols={1}
                                {...getFieldProps('tamper', {
                                    rules: [{ required: false }],
                                })}>
                                <List.Item arrow="horizontal">防拆情况</List.Item>
                            </Picker>

                            <List>
                                <List.Item arrow="down"
                                    onClick={() => {
                                        document.getElementsByTagName('body')[0].style.overflowY = 'hidden';
                                        this.setState({
                                            calendarShow: true,
                                        });
                                    }}>反馈时间区间</List.Item>
                                {
                                    this.state.startTime || this.state.endTime ?
                                        (
                                            <Flex
                                                style={{ backgroundColor: '#fff' }}
                                                wrap='nowrap'
                                                justify='center'>
                                                <List.Item>{this.state.startTime}</List.Item>
                                                ~
                                            <List.Item>{this.state.endTime}</List.Item>
                                            </Flex>
                                        ) : null
                                }
                                <Calendar
                                    locale={zhCN}
                                    showShortcut={true}
                                    onCancel={this.calendarCancel}
                                    onConfirm={this.calendarConfirm}
                                    visible={this.state.calendarShow}
                                    minDate={new Date('2019/1/1')}
                                    maxDate={new Date()}
                                >
                                </Calendar>
                            </List>
                            <WhiteSpace />
                            <WingBlank>
                                <Flex>
                                    <Flex.Item>
                                        <Button
                                            style={{ width: '100%' }}
                                            type="primary"
                                            htmlType="submit"
                                            onClick={this.searchSubmit}>查询</Button>
                                    </Flex.Item>
                                    <Flex.Item>
                                        <Button
                                            style={{ width: '100%' }}
                                            onClick={this.searchReset}>重置</Button>
                                    </Flex.Item>
                                </Flex>
                            </WingBlank>
                        </form>
                    ) : null}

                    {this.state.isSearch ?
                        (
                            <div>
                                <Divider>搜索结果有关图表</Divider>
                                <div style={{
                                    marginTop: 12,
                                    padding: 8,
                                    width: '100%',
                                    height: 250,
                                    backgroundColor: '#fff'
                                }}>

                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        {this.state.chartSearchData.timestamp.length == 0 ? (
                                            <Empty
                                                image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
                                                imageStyle={{
                                                    marginTop: 30,
                                                }}
                                                description={
                                                    <span style={{ color: '#7a7a7a' }}>
                                                        未接受到数据，请按照条件搜索以展示可视化图表
                                                </span>
                                                }
                                            />
                                        ) : (
                                                <ChartSmokeSearch
                                                    chartData={this.state.chartSearchData} />
                                            )}
                                    </Skeleton>
                                </div>
                            </div>
                        ) : null
                    }

                    {this.state.listLoading ?
                        (
                            <ActivityIndicator toast text="加载中..." />
                        ) :
                        (
                            <div>
                                <div>
                                    <Divider>设备状态总览</Divider>
                                    <Flex style={{ marginLeft: 10, marginRight: 10, marginBottom: 5 }}>
                                        <Flex.Item>
                                            <div
                                                className='wechatMyHistoryDataCard'
                                                style={{ backgroundColor: 'rgb(233, 217, 211)', }}>
                                                <div className='title'>设备总数</div>
                                                <div className='data'>{deviceStatusData['sum']}</div>
                                            </div>
                                        </Flex.Item>
                                        <Flex.Item>
                                            <div
                                                className='wechatMyHistoryDataCard'
                                                style={{ backgroundColor: 'rgb(233, 217, 211)', }}>
                                                <div className='title'>设备正常</div>
                                                <div className='data'>
                                                    {deviceStatusData['00']}
                                                    {deviceStatusData['00'] == 0 ? (null) : (
                                                        <span>/({(deviceStatusData['00'] / deviceStatusData['sum'] * 100).toFixed(0)}%)</span>
                                                    )}
                                                </div>
                                            </div>
                                        </Flex.Item>
                                    </Flex>
                                    <Flex style={{ marginLeft: 10, marginRight: 10, marginBottom: 5 }}>
                                        <Flex.Item>
                                            <div
                                                className='wechatMyHistoryDataCard'
                                                style={{ backgroundColor: 'rgb(210, 208, 223)', }}>
                                                <div className='title'>烟雾报警</div>
                                                <div className='data'>
                                                    {deviceStatusData['01']}
                                                    {deviceStatusData['01'] == 0 ? (null) : (
                                                        <span>/({(deviceStatusData['01'] / deviceStatusData['sum'] * 100).toFixed(0)}%)</span>
                                                    )}
                                                </div>
                                            </div>
                                        </Flex.Item>
                                        <Flex.Item>
                                            <div
                                                className='wechatMyHistoryDataCard'
                                                style={{ backgroundColor: 'rgb(207, 218, 213)', }}>
                                                <div className='title'>防拆异常</div>
                                                <div className='data'>
                                                    {deviceStatusData['02']}
                                                    {deviceStatusData['02'] == 0 ? (null) : (
                                                        <span>/({(deviceStatusData['02'] / deviceStatusData['sum'] * 100).toFixed(0)}%)</span>
                                                    )}
                                                </div>
                                            </div>
                                        </Flex.Item>
                                        <Flex.Item>
                                            <div
                                                className='wechatMyHistoryDataCard'
                                                style={{ backgroundColor: 'RGB(251,208,229)', }}>
                                                <div className='title'>电压异常</div>
                                                <div className='data'>
                                                    {deviceStatusData['03']}
                                                    {deviceStatusData['03'] == 0 ? (null) : (
                                                        <span>/({(deviceStatusData['03'] / deviceStatusData['sum'] * 100).toFixed(0)}%)</span>
                                                    )}
                                                </div>
                                            </div>
                                        </Flex.Item>
                                    </Flex>
                                    <Flex style={{ marginLeft: 10, marginRight: 10, marginBottom: 5 }}>
                                        <Flex.Item>
                                            <div
                                                className='wechatMyHistoryDataCard'
                                                style={{ backgroundColor: 'RGB(161,195,191)', }}>
                                                <div className='title'>通信故障</div>
                                                <div className='data'>
                                                    {deviceStatusData['04']}
                                                    {deviceStatusData['04'] == 0 ? (null) : (
                                                        <span>/({(deviceStatusData['04'] / deviceStatusData['sum'] * 100).toFixed(0)}%)</span>
                                                    )}
                                                </div>
                                            </div>
                                        </Flex.Item>
                                        <Flex.Item>
                                            <div
                                                className='wechatMyHistoryDataCard'
                                                style={{ backgroundColor: 'rgb(255, 194, 105)', }}>
                                                <div className='title'>设备故障</div>
                                                <div className='data'>
                                                    {deviceStatusData['05']}
                                                    {deviceStatusData['05'] == 0 ? (null) : (
                                                        <span>/({(deviceStatusData['05'] / deviceStatusData['sum'] * 100).toFixed(0)}%)</span>
                                                    )}
                                                </div>
                                            </div>
                                        </Flex.Item>
                                        <Flex.Item>
                                            <div
                                                className='wechatMyHistoryDataCard'
                                                style={{ backgroundColor: 'rgb(233, 233, 211)', }}>
                                                <div className='title'>其他故障</div>
                                                <div className='data'>
                                                    {deviceStatusData['06']}
                                                    {deviceStatusData['06'] == 0 ? (null) : (
                                                        <span>/({(deviceStatusData['06'] / deviceStatusData['sum'] * 100).toFixed(0)}%)</span>
                                                    )}
                                                </div>
                                            </div>
                                        </Flex.Item>
                                    </Flex>
                                </div>
                                <div>
                                    <Divider>数据列表</Divider>
                                    {cardList}
                                </div>
                            </div>
                        )
                    }
                </PullToRefresh>

                {pathname == '/' ? (
                    <div
                        className='hoverButtom'
                        onClick={this.handleHoverButtom}>
                        <div
                            style={{
                                width: 28,
                                height: 28,
                                margin: '0 auto',
                                position: 'relative',
                                top: '50%',
                                marginTop: -14,
                            }}>
                            <img
                                style={{ width: '100%', height: 'auto' }}
                                src={require('../img/search.png')}></img>
                        </div>
                    </div>
                ) : null}
            </div>
        )
    }
}
const WeChatSmokeDeviceMain = createForm()(weChatSmokeDeviceMain);

class ChartSmokeSearch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
        };
    }

    componentWillReceiveProps(props) {
        if (md5(props.chartData) != md5(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
            }, () => {
                this.drawChart();
            })
        }
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('ChartSmokeSearch'));

            let dataZoom;

            if (this.state.chartData.timestamp.length <= 30) {
                dataZoom = [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    start: (this.state.chartData.timestamp.length - 30) / this.state.chartData.timestamp.length * 100,
                    end: 100,
                }, {
                    start: (this.state.chartData.timestamp.length - 30) / this.state.chartData.timestamp.length * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            }

            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['反馈次数'],
                    top: 50
                },
                color: ['#2f4554', '#c23531'],
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '40px',
                    top: '30px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        magicType: { show: true, type: ['line', 'bar'] }
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: this.state.chartData.timestamp,
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name: '反馈次数',
                    type: 'value'
                },
                dataZoom: dataZoom,
                series: [{
                    name: '上报数',
                    type: 'line',
                    data: this.state.chartData.times,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                }]

            });
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='ChartSmokeSearch' style={chartStyle} />)
    }
}

class WeChatSmokeDeviceHistory extends Component {
    constructor(props) {
        super(props);
        this.state = {
            listLoading: true,
            listData: [],
            currentListData: [],
            currentDeviceId: this.props.location.state.deviceId === undefined ? null : this.props.location.state.deviceId,
            currentDeviceName: this.props.location.state.name === undefined ? null : this.props.location.state.name,
            currentDeviceAddress: this.props.location.state.address === undefined ? null : this.props.location.state.address,
            departmentId: this.props.location.state.departmentId === undefined ? null : this.props.location.state.departmentId,
            deviceStatusObject: {
                '00': '正常',
                '01': '烟雾报警',
                '02': '防拆异常',
                '03': '电压异常(电压低于2.9V)',
                '04': '通信故障',
                '05': '设备故障',
                '06': '其他故障'
            },

            refreshing: false,
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            listLoading: true
        });
        getSingleSmokeDeviceRecordApi(parseInt(this.state.departmentId), this.state.currentDeviceId)
            .then((res) => {
                let listData = [];
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    listData.push({
                        deviceStatus: item.deviceStatus,
                        fireAlarm: item.fireAlarm,
                        smokeConc: item.smokeConc,
                        envTemp: item.envTemp,
                        batteryVoltage: item.batteryVoltage,
                        tamper: item.tamper,
                        timestamp: item.timestamp,
                    });
                });
                this.setState({
                    listData: listData,
                    listLoading: false,
                });

                if (listData.length > 5) {
                    this.setState({
                        currentListData: listData.slice(0, 5),
                    });
                } else {
                    this.setState({
                        currentListData: listData.slice(0, listData.length),
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    listRefresh = () => {
        this.setState({ refreshing: true });
        let listData = [...this.state.listData];
        let currentListData = [...this.state.currentListData];
        setTimeout(() => {
            if (listData.length == currentListData.length) {
                message.info('已经是最后一条数据');
            } else if (listData.length - currentListData.length <= 5) {
                this.setState({ currentListData: listData });
            } else {
                this.setState({
                    currentListData: currentListData.concat(...[listData.slice(currentListData.length, currentListData.length + 5)])
                }, () => { console.log(this.state.currentListData.length) })
            }
            this.setState({ refreshing: false });
        }, 500);
    }


    render() {
        let cardList;
        if (this.state.currentListData.length != 0) {
            cardList = this.state.currentListData.map((value, index) => {
                let content = [{
                    title: '设备状态',
                    value: (
                        <div>
                            {value.deviceStatus == '00' ?
                                (
                                    <Tag color={'green'}>{this.state.deviceStatusObject[value.deviceStatus]}</Tag>
                                ) : (
                                    <Tag color={'red'}>{this.state.deviceStatusObject[value.deviceStatus]}</Tag>
                                )
                            }
                        </div>
                    )
                }, {
                    title: '火警状态',
                    value: (
                        <div>
                            {value.fireAlarm == 0 ? ('非火警') : ('火警')}
                        </div>
                    )
                }, {
                    title: '烟雾浓度',
                    value: (
                        <div>
                            {value.timestamp != 0 ? (<Tag color={'orange'}>{value.smokeConc} mg/m³</Tag>) : (
                                value.smokeConc == 0 ?
                                    (
                                        <Tag color={'green'}>正常无反馈</Tag>
                                    ) : (
                                        <Tag color={'orange'}>{value.smokeConc} mg/m³</Tag>
                                    )
                            )
                            }
                        </div>
                    )
                }, {
                    title: '环境温度',
                    value: (
                        <div>
                            {value.timestamp != 0 ? (value.envTemp + ' ℃') : (
                                value.envTemp == 0 ?
                                    (
                                        <Tag color={'green'}>正常无反馈</Tag>
                                    ) : (
                                        value.envTemp + ' ℃'
                                    )
                            )
                            }
                        </div>)
                }, {
                    title: '工作电压',
                    value: (<div>{value.batteryVoltage + ' V'}</div>)
                }, {
                    title: '防拆情况',
                    value: (
                        <div>
                            {value.tamper == '00' ?
                                (
                                    <Tag color={'green'}>正常</Tag>
                                ) : (
                                    <Tag color={'red'}>防拆盖脱离</Tag>
                                )
                            }
                        </div>
                    )
                }];

                let contentCard = content.map((d, index) =>
                    <Card
                        size="small"
                        title={d.title}
                        headStyle={{ padding: '0 8px' }}
                        bodyStyle={{ height: 38, padding: 8 }}
                        className='upAndDownInnerCardHalf'>
                        {d.value}
                    </Card>
                )

                return (
                    <Card
                        className='innerConditionCard'
                        style={{ margin: '10px' }}
                        headStyle={{ padding: '0 16px' }}
                        bodyStyle={{ padding: '10px' }}
                        title={value.timestamp}>
                        <Flex
                            justify="between"
                            wrap='wrap'
                            style={{ marginBottom: '-8px' }}>
                            {contentCard}
                        </Flex>
                    </Card>
                )
            });
        } else {
            cardList = (<Empty />);
        }

        return (
            <div>
                <PullToRefresh
                    style={{
                        height: document.documentElement.clientHeight,
                        overflow: 'auto',
                    }}
                    damping={60}
                    ref={el => this.ptr = el}
                    indicator={{ deactivate: '上拉可以刷新', }}
                    direction={'up'}
                    refreshing={this.state.refreshing}
                    onRefresh={this.listRefresh}>
                    <Divider>设备数据</Divider>
                    <Card
                        className='conditionCard'
                        style={{ textAlign: 'center', margin: '8px 24px' }}
                        size="small"
                        title={'设备编号'}>
                        {this.state.currentDeviceId}
                    </Card>
                    <Card
                        className='conditionCard'
                        style={{ textAlign: 'center', margin: '8px 24px' }}
                        size="small"
                        title={'设备名称'}>
                        {this.state.currentDeviceName}
                    </Card>
                    <Card
                        className='conditionCard'
                        style={{ textAlign: 'center', margin: '8px 24px' }}
                        size="small"
                        title={'设备地址'}>
                        {this.state.currentDeviceAddress}
                    </Card>

                    {this.state.listLoading ?
                        (
                            <ActivityIndicator toast text="加载中..." />
                        ) :
                        (
                            <div>
                                <Divider>反馈历史</Divider>
                                {cardList}
                            </div>
                        )
                    }
                </PullToRefresh>
            </div>
        )
    }



}






export default WeChatSmokeDevice;